<?php

namespace App\Task;

use Hyperf\Redis\Redis;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class BaseSyncTask extends AbstractBaseTask
{
    protected Redis $redis;
    const int UpdateKeyExpire = 10 * 86400;
    const string UpdateKeyPrefix = 'up:';
    protected array $dataExpire = ['odds' => 300, 'stats' => 600, 'trend' => 120, 'incidents' => 120, 'lineup' => 1800, 'text_lives' => 120, 'analysis' => 1800, 'team_stats' => 3600, 'news' => 3600, 'tables' => 3600];
    protected array $curMatchUpdateInfo = [];
    protected string $curMatchId = '';
    protected string $updateKey = '';

    public function execute(): void
    {
        try {
            $this->redis = $this->container->get(Redis::class);
        } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) {
            $this->logger->error('redis连接获取失败');
            return;
        }
    }

    /**
     * 设置数据缓存时间
     * @param $type
     * @param $expire
     * @return void
     */
    protected function setDataExpire($type, $expire): void
    {
        $this->dataExpire[$type] = $expire;
    }

    protected function syncInit($matchId): void
    {
        try {
            $this->updateKey = self::UpdateKeyPrefix . $matchId;
            $this->curMatchUpdateInfo = $this->redis->hGetAll($this->updateKey);
            if (empty($this->curMatchUpdateInfo)) {
                $this->redis->hSet($this->updateKey, 'init', time());
            } else {
                $this->redis->expire($this->updateKey, self::UpdateKeyExpire);
            }
            $this->curMatchId = $matchId;
        } catch (\RedisException $e) {
            $this->logger->warning('redis命令执行失败');
        }
    }

    /**
     * 是否需要同步
     * @param $type
     * @return bool
     */
    protected function toSync($type): bool
    {
        if (!isset($this->dataExpire[$type]) || !isset($this->curMatchUpdateInfo[$type]) || time() - (int)$this->curMatchUpdateInfo[$type] > $this->dataExpire[$type]) {
            return true;
        }
        return false;
    }

    /**
     * 设置同步时间
     * @param $type
     * @return void
     */
    protected function setSyncFlag($type): void
    {
        if ($this->redis) {
            try {
                $this->redis->hSet('up:' . $this->curMatchId, $type, time());
            } catch (\RedisException $e) {
            }
        }
    }
}